package com.example.learn01.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.server.HttpServerResponse;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.learn01.common.Result;
import com.example.learn01.controller.dto.UserDTO;
import com.example.learn01.utils.TokenUtils;
import org.springframework.boot.json.JsonParser;
import org.springframework.boot.json.JsonParserFactory;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

import com.example.learn01.service.IUserService;
import com.example.learn01.entity.User;

import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author baomidou
 * @since 2024-04-09
 */
@RestController
@RequestMapping("/user")
public class UserController {
      //实现依赖注入
        @Resource
        private IUserService userService;

       //新增或更新
        @PostMapping
        public Boolean save(@RequestBody User user) {
            return userService.saveOrUpdate(user);
        }
        //删除
        @DeleteMapping("/{id}")
        public Boolean delete(@PathVariable Integer id) {
            return userService.removeById(id);
        }
        //查询
        @GetMapping
        public List<User> findAll() {
            return userService.list();
        }
        //根据id查询
        @GetMapping("/{id}")
        public User findOne(@PathVariable Integer id) {
            return userService.getById(id);
        }
        //分页查询
        @PostMapping("/page")
        public Result findPage(@RequestBody String jsonData) {
            // 手动解析JSON数据为Map对象
            JsonParser jsonParser = JsonParserFactory.getJsonParser();
            Map<String, Object> jsonMap = jsonParser.parseMap(jsonData);
            Integer pageNum = (Integer) jsonMap.get("pageNum");
            Integer pageSize = (Integer) jsonMap.get("pageSize");
            Result res= new Result();
            return res.success("success",userService.page(new Page<>(pageNum, pageSize)));
//            return userService.page(new Page<>(pageNum, pageSize));
        }
    @GetMapping("/export")
    public void export(HttpServletResponse response) throws Exception{
     // 从数据库查询所有数据
        List<User> list = userService.list();
    // 在内存操作，写出到浏览器
        ExcelWriter writer= ExcelUtil.getWriter(true);
//        writer.addHeaderAlias("username","用户名");
//        writer.addHeaderAlias("password","密码");
//        writer.addHeaderAlias("nickname","昵称");
     //一次性写出list的内容的对象到Excel，使用默认模式，强制输出标题
        writer.write(list,true);
        // 设置浏览器响应的格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("Notice信息表.xlsx", "UTF-8");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"; filename*=utf-8''" + fileName);

        User test= TokenUtils.getCurrentUser();
        System.out.println(test);
        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        out.close();
        writer.close();
    }

    @PostMapping("/import")
    public Boolean imp(MultipartFile file) throws Exception {
        InputStream inputStream = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);
        // 通过 javabean的方式读取Excel内的对象，但是要求表头必须是英文，跟javabean的属性要对应起来
       // List<User> list = reader.readAll(User.class);
       //return userService.saveBatch(list);
       // 当表头为中文时设置
        List<List<Object>> list= reader.read(1);
        List<User> users= CollUtil.newArrayList();
        for(List<Object> row : list){
            User user=new User();
            user.setUsername(row.get(0).toString());
            users.add(user);
        }
        return userService.saveBatch(users);
    }

    //查询
    @PostMapping("/login")
    public Result login(@RequestBody UserDTO userDTO) {
        return userService.login(userDTO);
    }


}
